package com.sl.plugin.step.maven.compile;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.io.LineHandler;
import cn.hutool.core.io.StreamProgress;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RuntimeUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.ZipUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.system.JvmInfo;
import cn.hutool.system.OsInfo;
import cn.hutool.system.SystemUtil;
import cn.hutool.system.UserInfo;
import com.sl.core.engine.meta.impl.AbstractProcessCompDescriptor;
import com.sl.core.engine.step.ProcessCompService;
import com.sl.core.engine.step.impl.AbstractProcessComp;
import lombok.SneakyThrows;
import org.apache.commons.compress.utils.Lists;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 *
 */
public class MavenCompileComp extends AbstractProcessComp<Map<String, Object>, String> implements ProcessCompService {


    public MavenCompileComp(AbstractProcessCompDescriptor abstractProcessCompDescriptor) {
        super(abstractProcessCompDescriptor);
    }

    @SneakyThrows
    @Override
    public String input(Map<String, Object> driver) {
        //先判断是否存在maven包 如果不存在则要去下载 todo
        String buildPath = meta.getStrAttr("buildPath");
        String cmd = meta.getStrAttr("cmd");
        String setting = meta.getStrAttr("setting");

        File file = mkOrReturn();

        OsInfo osInfo = SystemUtil.getOsInfo();
        Process s = null;
        String result = null;
        String execCmd = null;

        String javaHome = null;
        String property = System.getProperty("java.home");
        if (StrUtil.isNotBlank(property)) {
            javaHome = property;
        } else {
            throw new RuntimeException("没有jdk环境");
        }
        if (osInfo.isLinux() || osInfo.isMac() || osInfo.isMacOsX()) {
            s = RuntimeUtil.exec(new String[]{}, file, "chmod a+x ." + File.separator + "bin" + File.separator + "mvn");
            result = RuntimeUtil.getResult(s);
            logBasic(result);

            //设置java_home
            File mvnFile = FileUtil.file(file, "bin/mvn");
            String mvnFileStr = FileUtil.readString(mvnFile, Charset.defaultCharset());
            if (!StrUtil.contains(mvnFileStr, "export JAVA_HOME")) {
                mvnFileStr = "export JAVA_HOME=" + javaHome + "\n" + mvnFileStr;
                FileUtil.writeString(mvnFileStr, mvnFile, Charset.defaultCharset());
            }
            // export JAVA_HOME=/www/server/java/jdk-21.0.2;
            s = RuntimeUtil.exec(new String[]{}, file, "." + File.separator + "bin" + File.separator + "mvn -v");
            result = RuntimeUtil.getResult(s);
            logBasic(result);
            ///Users/weixin/Library/Java/JavaVirtualMachines/corretto-21.0.4/Contents/Home/bin/java -Dmaven.multiModuleProjectDirectory=/Users/weixin/work/project/self/square_lake -Djansi.passthrough=true -Dmaven.home=/Users/weixin/Applications/IntelliJ IDEA Ultimate.app/Contents/plugins/maven/lib/maven3 -Dclassworlds.conf=/Users/weixin/Applications/IntelliJ IDEA Ultimate.app/Contents/plugins/maven/lib/maven3/bin/m2.conf -Dmaven.ext.class.path=/Users/weixin/Applications/IntelliJ IDEA Ultimate.app/Contents/plugins/maven/lib/maven-event-listener.jar -javaagent:/Users/weixin/Applications/IntelliJ IDEA Ultimate.app/Contents/lib/idea_rt.jar=61003:/Users/weixin/Applications/IntelliJ IDEA Ultimate.app/Contents/bin -Dfile.encoding=UTF-8 -Dsun.stdout.encoding=UTF-8 -Dsun.stderr.encoding=UTF-8 -classpath /Users/weixin/Applications/IntelliJ IDEA Ultimate.app/Contents/plugins/maven/lib/maven3/boot/plexus-classworlds.license:/Users/weixin/Applications/IntelliJ IDEA Ultimate.app/Contents/plugins/maven/lib/maven3/boot/plexus-classworlds-2.8.0.jar org.codehaus.classworlds.Launcher -Didea.version=2024.2.2 -T 4 install
            execCmd = File.separator + "bin" + File.separator + "mvn clean " + cmd + " -f " + buildPath;

        } else if (osInfo.isWindows()) {

            //设置java_home
            File mvnFile = FileUtil.file(file, "bin/mvn.cmd");
            String mvnFileStr = FileUtil.readString(mvnFile, Charset.defaultCharset());
            if (!StrUtil.contains(mvnFileStr, "set JAVA_HOME")) {
                mvnFileStr = "set JAVA_HOME=" + javaHome + "\n" + mvnFileStr;
                FileUtil.writeString(mvnFileStr, mvnFile, Charset.defaultCharset());
            }

            s = RuntimeUtil.exec(new String[]{}, file, "." + File.separator + "bin" + File.separator + "mvn.cmd -v");
            result = RuntimeUtil.getResult(s);
            logBasic(result);
            execCmd = File.separator + "bin" + File.separator + "mvn.cmd clean " + cmd + " -f " + buildPath;

        } else {
            logBasic("不支持的系统");
            return null;
        }

        if (StrUtil.isNotBlank(setting)) {
            execCmd += " -s " + setting;
        }

        logBasic("执行的mvn命令是" + file.getAbsolutePath() + execCmd);
        s = RuntimeUtil.exec(new String[]{}, file, "." + execCmd);
        InputStream in = null;
        List<String> resultList = Lists.newArrayList();
        try {
            in = s.getInputStream();
            IoUtil.readLines(in, Charset.defaultCharset(), (LineHandler) v -> {
                logBasic(v);
                resultList.add(v);
            });
        } finally {
            IoUtil.close(in);
            RuntimeUtil.destroy(s);
        }
        String collect = resultList.stream().collect(Collectors.joining("\n"));
        return collect;
    }

    // +https://dlcdn.apache.org/maven/maven-3/3.9.4/binaries/apache-maven-3.9.4-bin.zip

    @SneakyThrows
    private File mkOrReturn() {
        UserInfo userInfo = SystemUtil.getUserInfo();
        String homeDir = userInfo.getHomeDir();

        String ff = homeDir + File.separator + "maven" + File.separator + "apache-maven";
        File file = new File(ff);

        if (FileUtil.exist(file)) {
            logBasic("获取到了文件夹，直接返回");
            return file;
        }
        logBasic("没有获取到文件夹，需要下载");
        file = FileUtil.mkdir(homeDir + File.separator + "maven" + File.separator + "temp");

        File dfile = FileUtil.file(file, "download.zip");
        FileOutputStream fileOutputStream = new FileOutputStream(dfile);
        //下载
        HttpUtil.download("https://dlcdn.apache.org/maven/maven-3/3.9.4/binaries/apache-maven-3.9.4-bin.zip", fileOutputStream, true, new StreamProgress() {
            @Override
            public void start() {

            }

            @Override
            public void progress(long total, long progressSize) {
                logBasic("下载进度" + progressSize + "/" + total);
            }

            @Override
            public void finish() {

            }
        });
        File unzip = ZipUtil.unzip(dfile);

        List<File> files = FileUtil.loopFiles(unzip, 1, v -> true);
        if (CollUtil.isEmpty(files)) {
            return null;
        }
        File file2 = files.get(0);
        File rename = FileUtil.rename(file2, "apache-maven", true);

        File file1 = new File(ff);
        FileUtil.copyContent(rename, file1, true);
        FileUtil.del(dfile);
        FileUtil.del(unzip);
        return file1;

    }
}
